//
//  PlayCityTour.swift
//  ImGuider X
//
//  Created by 王鹏宇 on 10/25/18.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit
import MapKit

let  PopViewH = 60
let  PopViewW = kScreenWidth - 40
let  upOrDownH = 20
let  foldH = (ISiPhone5 || ISiPhone4) ?  ((kScreenWidth + 112) - pageViewW/16*7)  : (kScreenWidth + 112)

let  toBottom = 120 + kBottomHeight

let  pageViewW = PopViewW - 32
let  pageViewH =  (ISiPhone5 || ISiPhone4) ? pageViewW/16*9 : pageViewW


class PlayCityTour: BasePlayVC,PlayBarDelegate {
    
    
    @IBOutlet weak var playView: UIView!
    @IBOutlet weak var mapView: MKMapView!
    
    var playBar : PlayBar!
    
    var popView : UIView!
    var pageView : OtherDetailHeadView!
    
    var lineCollectionView : UICollectionView!
    var upOrDownBtn : UIButton!
    var startOrEndLabel : UILabel!
    var scenicPointLabel : UILabel!
    var lastDistance : CGFloat = 0
    var dropListView : X_DropListView!
    
    var viewmodel:PlayViewModel = PlayViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setup()
        setupPopView()
        setupData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if !isPlayAlways {
            WPY_AVPlayer.playManager.stop()
        }
    }
}


extension PlayCityTour {
    
    func setup(){
        
        playBar = PlayBar(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 110))
        playBar.delegate = self
        self.playView.addSubview(playBar)
        
        let rightItem = UIBarButtonItem(image: UIImage(named:"more"), style: .plain, target: self, action: #selector(goMore))
        self.navigationItem.rightBarButtonItem = rightItem
        
        self.dropListView = X_DropListView.SetupDropListView(frame: CGRect(x: kScreenWidth - 115, y: kNavigationBarHeight - 15, width: 110, height: 100), typeList: [ListType.AutomaticType,ListType.LoopBtnType], contentView: self.view)
        
        setNavBarStyle(.translucence)
    }
    
    func setupData(){
        
        LocationManager.share.startUpdatingLocation()
        
        viewmodel.reloadData()
        
        viewmodel.reloadMapFinished = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            if let anns = self.viewmodel.anns {
                
                self.mapView.removeAnnotations(self.mapView.annotations)
                
                self.mapView.addAnnotations(anns)
                
                self.setMapCenter()
                
                if AppManager.share.automaticPlay {
                    
                    self.viewmodel.statrtAutoplayTimer()
                }
            }
        }
        
        viewmodel.loadFinished = {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            if let errmsg = errmsg {
                
                self.view.makeToast(errmsg)
            }
            
            self.viewmodel.reloadMapdata()
            
            self.lineCollectionView.reloadData()
            if let count = self.viewmodel.records?.count , count > 0 {
                
                WPY_AVPlayer.playManager.musicArray = self.viewmodel.records!
                WPY_AVPlayer.playManager.lineModel = self.viewmodel.line
                
                self.selectCellWithIndex(index: 0, immediately: false)
            }
        }
        
        viewmodel.reloadRecord = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.pageView.pics = self.viewmodel.currentPics
        }
        
        viewmodel.mapDrawLineAction = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            
            self.drawLineAction()
        }
        
        viewmodel.progressText = {
            
            [weak self] msg in
            guard let `self` = self else { return }
            
            self.playBar.downloadBtn.setTitle(msg, for: .normal)
            self.playBar.downloadBtn.setImage(nil, for: .normal)
        }
        
        viewmodel.autoPlayAction = {
            
            [weak self] ann,alert in
            guard let `self` = self,
                let record = ann.model as? Record,
                let index = self.viewmodel.anns?.firstIndex(of: ann) else { return }
            
            
            if alert {
                
                
                
                IGAlertVC.show(vc: self, title: nil, message:String.localizedStringWithFormat(LocalizedString("auto_play_tips"), record.spotname ?? "",record.spotname ?? ""), commit: (LocalizedString("switch"),{
                    
                    self.selectCellWithIndex(index: index, immediately: true)
                }), cancel: (LocalizedString("cancel"),nil))
            } else {
                
                self.selectCellWithIndex(index: index, immediately: true)
            }
        }
        
        self.dropListView.automaticChanged = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            if AppManager.share.automaticPlay {
                
                self.viewmodel.statrtAutoplayTimer()
            } else {
                
                self.viewmodel.stopAutoplayTimer()
            }
        }
    }
    
    func setupPopView(){
        
        let locationBtn = UIButton(frame: CGRect(x: kScreenWidth - 60, y: kScreenHeight - PopViewH - toBottom - 50, width: 40, height: 40))
        locationBtn.setBackgroundImage(UIImage(named: "当前位置"), for: UIControl.State.normal)
        locationBtn.addTarget(self, action: #selector(goLocation), for: UIControl.Event.touchUpInside)
        self.view.addSubview(locationBtn)
        
        let mapBtn =  UIButton(frame: CGRect(x: kScreenWidth - 116, y: kScreenHeight - PopViewH - toBottom - 50, width: 40, height: 40))
        mapBtn.setBackgroundImage(UIImage(named: "导航1"), for: UIControl.State.normal)
        mapBtn.addTarget(self, action: #selector(goGuide), for: UIControl.Event.touchUpInside)
        self.view.addSubview(mapBtn)
        
        popView = UIView(frame: CGRect(x: 20, y: kScreenHeight - PopViewH - toBottom, width: PopViewW, height: PopViewH))
        popView.backgroundColor = UIColor.white
        
        popView.clipsToBounds = true
        self.view.addSubview(popView)
        
        upOrDownBtn = UIButton(frame: CGRect(x: 10, y: 0, width: PopViewW - 20, height: upOrDownH))
        upOrDownBtn.setImage(UIImage(named: "foldIcon"), for: UIControl.State.normal)
        upOrDownBtn.addTarget(self, action: #selector(upOrDownBtnClicked(sender:)), for: UIControl.Event.touchUpInside)
        self.popView.addSubview(upOrDownBtn)
        
        startOrEndLabel = UILabel(frame: CGRect(x: 8, y: 22.5, width: 25, height: 25))
        startOrEndLabel.layer.cornerRadius = 12.5
        startOrEndLabel.clipsToBounds = true
        startOrEndLabel.textColor = UIColor.white
        startOrEndLabel.font = kFont14
        startOrEndLabel.textAlignment = .center
        startOrEndLabel.backgroundColor = UIColor.hexStringToColor(hexString: "#222222")
        self.popView.addSubview(startOrEndLabel)
        
        
        
        scenicPointLabel = UILabel(frame: CGRect(x: 40, y: 20, width: PopViewW - 48, height: 30))
        scenicPointLabel.font = kFont14
        scenicPointLabel.adjustsFontSizeToFitWidth = true
        scenicPointLabel.minimumScaleFactor = 0.7
        scenicPointLabel.textColor = kSubitleColor
        self.popView.addSubview(scenicPointLabel)
        
        
        
        pageView = OtherDetailHeadView(frame: CGRect(x: 16, y: 60, width: pageViewW, height: pageViewH))
        self.popView.addSubview(pageView)
        pageView.backgroundColor = UIColor.red
        
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        //        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.itemSize = CGSize(width: 70, height: 110)
        self.lineCollectionView = UICollectionView(frame: CGRect(x: 16, y: pageViewH + 72, width: PopViewW - 32, height: 110), collectionViewLayout: layout)
        
        self.lineCollectionView.delegate = self
        self.lineCollectionView.dataSource = self
        self.lineCollectionView.clipsToBounds = false
        self.lineCollectionView.backgroundColor = UIColor.white
        self.popView.addSubview(self.lineCollectionView)
        self.lineCollectionView.showsHorizontalScrollIndicator = false
        
        self.lineCollectionView.register(UINib(nibName: "RecordCell", bundle: nil), forCellWithReuseIdentifier: "RecordCell")
        
        self.popView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(panPopView(pan:))))
    }
}


extension PlayCityTour {
    
    private func selectCellWithIndex(index : Int,immediately : Bool){
        
        changeScenicPointWithIndex(index: index)
        
        self.playBar.playMusicWithIndex(index: index, immediately: immediately)
    }
    
    func changePointTo(index: Int) {
        
        changeScenicPointWithIndex(index: index)
    }
    
    func changeMapPoint(index:Int) {
        
        if index == viewmodel.lastMapviewIndex {
            
            return
        }
        
        guard let ann = viewmodel.anns?[index],
            let annView = mapView.view(for: ann) as? TripAnnotionView else {
                
                self.setMapCenter()
                
                self.changeMapPoint(index: index)
                return
        }
        
        if let lastindex = viewmodel.lastMapviewIndex, let lastAnn = viewmodel.anns?[lastindex] {
            
            let lastAnnView =  mapView.view(for: lastAnn) as? TripAnnotionView
            lastAnnView?.hiddenRecordView()
        }
        
        annView.showRecordView()
        
        viewmodel.lastMapviewIndex = index
        
        drawLineAction()
        
        if viewmodel.hasDrawLine {
            
            viewmodel.statrtDrawTimer()
        }
        
        setMapCenter(ann.coordinate)
    }
    
    func setMapCenter(_ coor:CLLocationCoordinate2D? = nil) {
        
        guard let coor = coor else {
            
            if let anns = viewmodel.anns {
                
                mapView.showAnnotations(anns, animated: false)
            }
            
            return
        }
        
        mapView.setCenter(coor, animated: true)
    }
    
    func mapviewTrackAction() {
        
        if viewmodel.hasDrawLine {
            
            self.mapView.setUserTrackingMode(.followWithHeading, animated: true)
            
        } else {
            
            mapView.setUserTrackingMode(.none, animated: true)
            
            if let lastindex = viewmodel.lastMapviewIndex, let lastAnn = viewmodel.anns?[lastindex] {
                
                setMapCenter(lastAnn.coordinate)
            } else {
                
                setMapCenter()
            }
        }
    }
    
    func drawLineAction() {
        
        guard let lastIndex = viewmodel.lastMapviewIndex, let ann = viewmodel.anns?[lastIndex] else {
            
            return
        }
        
        if let record = ann.model as? Record,
            let transport = record.transport {
            
            if transport != .normal && transport != .foot {
                
                return
            }
        }
        
        viewmodel.hasDrawLine = self.mapView.addLine(to: ann.coordinate) {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            self.makeToast(text: errmsg)
        }
    }
    
    
    func changeScenicPointWithIndex(index : Int){
        
        guard let record = self.viewmodel.records?[index] else {return}
        
        let indexPath = IndexPath(row: index, section: 0)
        
        if let cell = self.lineCollectionView.cellForItem(at: self.viewmodel.currentIndexPath) as? RecordCell {
            cell.isSelect = false
        }
        
        if let currentCell = self.lineCollectionView.cellForItem(at: indexPath) as? RecordCell {
            
            currentCell.isSelect = true
            
            self.lineCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
            
        }
        if let num = record.number {
            self.startOrEndLabel.text = "\(num)"
        }
        
        self.scenicPointLabel.text = record.spotname
        
        changeMapPoint(index: index)
        
        self.lineCollectionView.reloadData()
        self.viewmodel.currentIndexPath = indexPath
        self.viewmodel.currentRecord = record
    }
    
    func downloadAction() {
        
        viewmodel.downloadTapped()
    }
    
    @objc func goGuide(){
        
        if let coor = viewmodel.currentRecord?.coor {
            
            Util.tractfic(to: coor, vc: self)
        }
        
    }
    
    @objc func goLocation(){
        
        self.mapviewTrackAction()
    }
    
    @objc func goMore(){
        
        if self.dropListView.isHidden {
            self.dropListView.show()
        }else{
            self.dropListView.hidde()
        }
        
    }
    
    @objc func upOrDownBtnClicked(sender : UIButton){
        
        var popFrame = self.popView.frame
        
        if sender.isSelected {
            
            popFrame.origin.y = CGFloat(kScreenHeight - (PopViewH + toBottom))
            popFrame.size.height = CGFloat(PopViewH)
            //            self.open
            
        }else{
            
            popFrame.origin.y = CGFloat(kScreenHeight - foldH - toBottom)
            popFrame.size.height = CGFloat(foldH)
            
            //            self.off
        }
        
        //        var mapRect = self.mapView.frame
        //        mapRect.origin.y = (popFrame.origin.y - CGFloat((kScreenHeight - (PopViewH + toBottom)))) / 2.0
        
        UIView.animate(withDuration: 0.25, animations: {
            self.popView.frame = popFrame
            //            self.mapView.frame = mapRect
        })
        
        sender.isSelected = !sender.isSelected
    }
    
    @objc func panPopView(pan : UIPanGestureRecognizer){
        
        let distance = pan.translation(in: self.view)
        
        var popFrame = self.popView.frame
        popFrame.origin.y += distance.y - self.lastDistance
        popFrame.size.height += self.lastDistance - distance.y
        
        if Int(popFrame.origin.y) < (kScreenHeight - toBottom - foldH) {
            
            popFrame.origin.y = CGFloat(kScreenHeight - toBottom - foldH)
            popFrame.size.height = CGFloat(foldH)
            
        }
        
        if Int(popFrame.origin.y) > (kScreenHeight - PopViewH - toBottom){
            
            popFrame.origin.y = CGFloat(kScreenHeight - PopViewH - toBottom)
            popFrame.size.height = CGFloat(PopViewH)
            
        }
        
        self.popView.frame = popFrame
        self.lastDistance = distance.y
        
        //        var mapRect = self.mapView.frame
        //
        //        mapRect.origin.y = (popFrame.origin.y - CGFloat(kScreenHeight - toBottom - PopViewH)) / 2.0
        //        self.mapView.frame = mapRect
        
        if (pan.state == UIGestureRecognizer.State.ended){
            
            if distance.y > 0 {
                
                popFrame.origin.y = CGFloat(kScreenHeight - PopViewH - toBottom)
                popFrame.size.height = CGFloat(PopViewH)
                //                self.open
            }else{
                
                popFrame.origin.y = CGFloat(kScreenHeight - foldH - toBottom)
                popFrame.size.height = CGFloat(foldH)
                //                self.off
            }
            
            //            var maprect = self.mapView.frame
            //            maprect.origin.y = (popFrame.origin.y - CGFloat((kScreenHeight - (PopViewH + toBottom)))) / 2.0
            
            UIView.animate(withDuration: 0.25, animations: {
                
                self.popView.frame = popFrame;
                //                self.mapView.frame = mapRect;
                
            }) { (finished) in
                self.upOrDownBtn.isSelected = !self.upOrDownBtn.isSelected;
                self.lastDistance = 0;
            }
        }
    }
    
}


extension PlayCityTour: UICollectionViewDelegate,UICollectionViewDataSource {
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.viewmodel.records?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let  cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecordCell", for: indexPath) as! RecordCell
        
        if let record = self.viewmodel.records?[indexPath.row] {
            
            cell.record = record
            cell.isSelect = record == viewmodel.currentRecord
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if self.viewmodel.currentIndexPath.row == indexPath.row {
            return
        }
        self.selectCellWithIndex(index: indexPath.row, immediately: true)
    }
}

extension PlayCityTour: MKMapViewDelegate {
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        
        guard let ann = annotation as? TripAnnotion else {
            
            return nil
        }
        
        var view = mapView.dequeueReusableAnnotationView(withIdentifier: "TripAnnotionView") as? TripAnnotionView
        
        if view == nil {
            
            view = TripAnnotionView(annotation: ann, reuseIdentifier: "TripAnnotionView", anntype: .record)
        }
        
        view?.setup(ann: ann)
        
        view?.recordAction = {
            
            [weak self] ann in
            guard let `self` = self,
                let ann = ann,
                let index = self.viewmodel.anns?.firstIndex(of: ann) else { return }
            
            if index == self.viewmodel.lastMapviewIndex {
                
                return
            }
            
            self.selectCellWithIndex(index: index, immediately: true)
        }
        
        
        let index = viewmodel.anns?.firstIndex(of: ann)
        
        if index == viewmodel.lastMapviewIndex {
            
            view?.showRecordView()
        } else {
            
            view?.hiddenRecordView()
        }
        
        return view
    }
    
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        
        let render = MKPolylineRenderer(overlay: overlay)
        render.strokeColor = UIColor.hexStringToColor(hexString: "#00B8E4")
        render.lineWidth = 5
        
        return render
    }
}




